<?php
namespace utils;

class UtilsTool
{	
	static function unCompress($s, $f)
	{
		if(0==$f->blockSizeCpr) return $s;
		if(strlen($s) != $f->blockSizeCpr)
			throw new Up6Exception("recv block size ,send block size different",
		[strlen($s),$f]);
	    if (0 == strcasecmp($f->blockCprType, "zip")) 
			return UtilsTool::unZip($s);
	    return UtilsTool::unGzip($s);
	}
	
	static function decrypt($s, $f)
	{
		$blockSize = $f->blockSizeSec>0?$f->blockSizeSec:$f->blockSize;
		if(strlen($s) != $blockSize)
		{
			throw new Up6Exception("接收块大小与发送块大小不同",
		[$s,$f]);
		}

		//未加密
	    if(0==$f->blockSizeSec) return $s;
		
		//存储加密
		if(true==$f->encrypt) return $s;

		//解密
		$cry = new CryptoTool();
		return $cry->decrypt2($f->encryptAgo,$s);
	}
	
	static function check_md5($block,$md5Loc)
	{
	    if(empty($md5Loc)) return true;
	    $md5Svr = md5($block);
	    return StringTool::iequals($md5Svr,$md5Loc);
	}
	
	/// <summary>
	///
	/// </summary>
	/// <param name="s"></param>
	/// <param name="type">gzip,zip</param>
	/// <returns></returns>
	static function unGzip($s)
	{
		if(function_exists('gzdecode'))
			return gzdecode($s);
		return UtilsTool::gzdecode_diy($s);
	}

	/**
	 * 自定义的gzip解密方法
	 */
	static function gzdecode_diy($data) {
	  $flags = ord(substr($data, 3, 1));
	  $headerlen = 10;
	  $extralen = 0;
	  $filenamelen = 0;
	  if ($flags & 4) {
		  $extralen = unpack('v' ,substr($data, 10, 2));
		  $extralen = $extralen[1];
		  $headerlen += 2 + $extralen;
	  }
	  if ($flags & 8) // Filename
		  $headerlen = strpos($data, chr(0), $headerlen) + 1;
	  if ($flags & 16) // Comment
		  $headerlen = strpos($data, chr(0), $headerlen) + 1;
	  if ($flags & 2) // CRC at end of file
		  $headerlen += 2;
	  $unpacked = @gzinflate(substr($data, $headerlen));
	  if ($unpacked === FALSE)
		  $unpacked = $data;
	  return $unpacked;
	}
	
	static function unZip($s)
	{
	    return gzuncompress($s);
	}
	
}
?>